package com.hygj.service.impl;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.hygj.baseUtil.BaseDao;
import com.hygj.baseUtil.BaseServiceImpl;
import com.hygj.pojo.User;
import com.hygj.pojo.UserRole;
import com.hygj.service.UserRoleService;
import com.hygj.service.UserService;

@Service("userService")
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {

	@Resource
	UserRoleService userRoleService;

	@Resource(name = "userDao")
	@Override
	public void setDao(BaseDao<User> dao) {
		// TODO Auto-generated method stub
		super.setDao(dao);
	}

	@Override
	public User findUserByLoginName(String username) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("username", username);
		return (User) find("find", params);
	}

	/*
	 * uid 给用户赋予角色
	 */
	@Override
	public void grantUserRole(int uid, int[] rids) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("uid", uid); // 用户角色关联表 uid
		delete("delete", uid);
		if (rids.length > 0 && uid > 0) {
			UserRole userRole;
			for (int i = 0; i < rids.length; i++) {
				userRole = new UserRole(rids[i], uid);
				userRoleService.insert(userRole);
			}
		}

	}

	/**
	 * 添加用户使用(和修改用户信息时调用)
	 * 
	 */
	@Override
	public int saveUserwithRole(User user, String roles) {
		int a;
		if (user.getId() == null) {
			a = this.insert(user);
		} else {
			a = this.update("update", user);
			//userRoleService.delete("delete", user.getId());
		}
         // StringUtils.isNoneBlank 判断是否为空
		if (StringUtils.isNoneBlank(roles)) {
			//split() 方法用于把一个字符串分割成字符串数组。
			String[] r = roles.split(",");
			UserRole userRole;
			if (r.length > 0) {
				for (String _r : r) {
					//Integer.parseint()就是把整形对象Integer转换成基本数据类型int（整数）
					userRole = new UserRole(Integer.parseInt(_r), user.getId());
					userRoleService.insert(userRole);
				}
			}
		}

		return a;
	}

}
